<template>
  <div class="course">
    <!-- 搜索部分 -->
    <el-row :gutter="10" class="search-section">
      <el-col :span="6">
        <el-form-item label="部门名称：">
          <el-input v-model="filters.name" placeholder="请输入部门名称"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="部门状态：">
          <el-select v-model="filters.status" placeholder="请选择部门状态" style="width: 240px">
            <el-option label="正常" :value="0"></el-option><!-- 注意这里的 :value 用来绑定数字 -->
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :span="6">
        <el-button type="primary" :icon="Search" @click="searchDepartment">搜索</el-button>
        <el-button :icon="Refresh" @click="resetFilters">重置</el-button>
      </el-col>
    </el-row>

    <!-- 按钮部分 deleteSelectedNews-->
    <div class="button-section">
      <el-button type="primary" plain :icon="Plus" @click="openAddDialog">新增</el-button>
      <!-- 展开/折叠按钮 -->
      <el-button type="primary" @click="toggleAll">{{ allExpanded ? '全部折叠' : '全部展开' }}</el-button>
    </div>
    <!-- 表头 -->
    <div class="tableHeaed">
      <el-row :gutter="20">
        <el-col :span="5">
          <el-form-item>
            <span class="label-text">部门名称</span>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item>
            <span class="label-text">排序</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <span class="label-text">创建时间</span>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <span class="label-text">状态</span>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <span class="label-text">操作</span>
          </el-form-item>
        </el-col>
      </el-row>
    </div>
    <!-- 模拟表格 -->
    <div class="demo-collapse">
      <el-collapse class="1stClass" v-model="allExpandedNames">
        <el-collapse-item name="1">
          <template #title>
            <!-- <span v-html="rootData[0].name + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + rootData[0].id"></span> -->
            <!-- {{ rootData[0].name }} + {{ rootData[0].name }} -->
            <span class="nameclp">{{ rootData[0].name }}</span>
            <span class="stateclp">正常</span>
            <span>
              <el-button type="primary" link size="small" @click.stop.prevent="addDepartment(0, rootData[0])"
                :icon="Plus">新增</el-button>
            </span>
          </template>

          <!-- 第二级 -->
          <div>
            <el-collapse class="2ndClass" v-model="allExpandedNames">
              <el-collapse-item v-for="item in tableData" :key="item.companyId" :name="item.name">
                <template #title> <!-- 使用 v-slot 的方式传递 name 属性 -->
                  <!-- <span class="nameclp2nd" v-html="'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + item.name"></span> -->
                  <span class="nameclp2nd">{{ item.name }}</span>
                  <span class="stateclp">正常</span>
                  <span class="sndBtn1">
                    <el-button type="primary" link size="small" @click.stop.prevent="addDepartment(0, item)"
                      :icon="Plus">新增</el-button>
                  </span>
                  <span>
                    <el-button type="primary" link size="small" @click.stop.prevent="editMeetings(0, item)"
                      :icon="EditPen">修改</el-button>
                  </span>
                </template>
                <!-- el-collapse-item 的内容 -->
                <!-- 第三级 -->
                <div>
                  <el-collapse class="3rdClass" v-model="allExpandedNames">
                    <el-collapse-item v-for="deprt in item.departmentList" :key="deprt.index" :name="deprt.name">
                      <template #title> <!-- 使用 v-slot 的方式传递 name 属性 -->
                        <span class="nameclp3rd">{{ deprt.name }}</span>
                        <span class="index">{{ deprt.index }}</span>
                        <span class="creat_time">{{ deprt.create_time }}</span>
                        <span class="stateclp3rd" v-if="deprt.status == 1">停用</span>
                        <span class="stateclp3rd" v-if="deprt.status == 0">正常</span>
                        <span class="trdBtn1">
                          <el-button type="primary" link size="small" :icon="Delete"
                            @click.stop.prevent="deleteDepartment(0, deprt)">删除</el-button>
                        </span>
                        <span>
                          <el-button type="primary" link size="small" @click.stop.prevent="editMeetings(0, deprt)"
                            :icon="EditPen">修改</el-button>
                        </span>
                      </template>
                      <!-- el-collapse-item 的内容 -->
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>

        </el-collapse-item>
      </el-collapse>
    </div>



    <el-dialog title="添加部门" v-model="dialogVisible" style="width: 50%;">
      <el-form :model="tableData" label-width="90px">
        <el-form-item label="上级部门" required>
          <el-select v-model="addFormData.company_name" placeholder="上级部门" size="large" style="width: 240px">
            <el-option v-model="rootData" :key="rootData[0].name" :label="rootData[0].name" :value="rootData[0].name" />
            <el-option v-for="item in tableData" :key="item.name" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门名称" required>
              <el-input v-model="addFormData.name" placeholder="请输入部门名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" required>
              <el-input-number v-model="addFormData.index" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" required>

          <el-radio-group v-model="addFormData.status" class="ml-4">
            <el-radio :value="0" size="large">正常</el-radio>
            <el-radio :value="1" size="large">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input v-model="contact.name" placeholder="请输入负责人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" style="width: 240px;">
              <el-input v-model="contact.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" style="width: 330px;">
          <el-input v-model="contact.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>

    <!--修改部门-->
    <el-dialog title="修改部门" v-model="dialogVisible1" style="width: 50%;">
      <el-form :model="tableData" label-width="90px">
        <el-form-item label="上级部门" required>
          <el-select v-model="updateFormData.company_name" placeholder="上级部门" size="large" style="width: 240px">
            <el-option v-model="rootData" :key="rootData[0].name" :label="rootData[0].name" :value="rootData[0].name" />
            <el-option v-for="item in tableData" :key="item.name" :label="item.name" :value="item.name"
              :disabled="updateFormData.company_name === '测盟汇'" />
          </el-select>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="部门名称" required>
              <el-input v-model="updateFormData.name" placeholder="请输入部门名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" required>
              <el-input-number v-model="updateFormData.index" controls-position="right" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" required>

          <el-radio-group v-model="updateFormData.status" class="ml-4">
            <el-radio :value="0" size="large">正常</el-radio>
            <el-radio :value="1" size="large">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input v-model="contact.name" placeholder="请输入负责人姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" style="width: 240px;">
              <el-input v-model="contact.phone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" style="width: 330px;">
          <el-input v-model="contact.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible1 = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm1">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, Ref, computed, onMounted } from 'vue';
import { Plus, Edit, Delete, Download, EditPen, Search, Refresh } from '../../../node_modules/@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElTable, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElCheckbox, FormInstance } from 'element-plus';
import { type Filters, type DepartmentItem, type Company, type ContactInfo, getCompanyList, addDepartmentService, updateDepartmentService, deleteDepartmentService, getContactInfo, searchDepartmentService } from '../../api/departmentApi.ts'

const filters: Ref<Filters> = ref({
  name: '',
  status: null

});

const tableData: Ref<Company[]> = ref([

]);
const rootData = ref([
  {
    id: 0,  // 为根节点指定一个唯一的ID
    name: "测盟汇",
    departmentList: tableData.value
  }
]);

const formatStatus = (row: any) => {

  if (row.status) {
    return row.status === 0 ? '正常' : '停用';
  } else {
    return '正常';
  }

};
function enrichDataWithParentReference(departments: any, parent = null) {
  return departments.map((department: any) => {
    department.parent = parent;  // 每个节点都保存一个对其父节点的引用
    if (department.departmentList && department.departmentList.length > 0) {
      department.departmentList = enrichDataWithParentReference(department.departmentList, department);
    }
    return department;
  });
}

const fetchDepartments = async () => {
  try {
    const originalData = await getCompanyList(); // 获取原始数据
    tableData.value = enrichDataWithParentReference(originalData);// 为每个节点添加一个指向其父节点的引用

    rootData.value = [
      {
        id: 0,
        name: "测盟汇",
        departmentList: tableData.value
      }
    ];
  } catch (error) {

    console.error("获取会议列表失败", error);
  }

};
fetchDepartments();
// 搜索部门
const searchDepartment = async () => {
  try {
    const originalData = await searchDepartmentService(filters.value); // 获取原始数据
    tableData.value = enrichDataWithParentReference(originalData);// 为每个节点添加一个指向其父节点的引用

    rootData.value = [
      {
        id: 0,
        name: "测盟汇",
        departmentList: tableData.value
      }
    ];
    ElMessage.success('搜索成功');
  } catch (error) {

    console.error("获取会议列表失败", error);
  }

};
// 重置搜索条件
const resetFilters = () => {
  filters.value = {
    name: '',
    status: null
  };
  fetchDepartments();
  ElMessage.success('重置成功');
};


// 添加部门
const dialogVisible = ref(false);
const addFormData = ref<DepartmentItem>({
  name: '',
  status: null,
  index: null,
  company_name: '',
  create_time: '',
  id: null,
});
const contact = ref<ContactInfo>({
  name: '',
  phone: '',
  email: ''
});
const openAddDialog = () => {
  dialogVisible.value = true;
};
const resetForm = () => {
  addFormData.value = {
    name: '',
    status: null,
    index: null,
    company_name: '',
    create_time: '',
    id: null,
  };
  updateFormData.value = {
    name: '',
    status: null,
    index: null,
    company_name: '',
    create_time: '',
    id: null,
  };
  contact.value = {
    name: '',
    phone: '',
    email: ''
  };
   //重置表单和重置验证状态
   if (ruleForm.value) {
        ruleForm.value.resetFields();
    }
  
};
//------获取当前登录的用户信息
import { useUserInfoStore } from '../../store/userInfo.ts'
const userInfoStore = useUserInfoStore()
const userName = userInfoStore.info.name
const company_name = userInfoStore.info.company_name

//添加子部门
const addDepartment = (index: number, row: any) => {
  console.log(index);
  console.log(row)
  addFormData.value = {
    name: '',
    index: null,
    create_time: '',
    company_name: row.name,
    id: null,
    status: null,
  };
  if (userName !== 'admin') {
    addFormData.value.company_name = company_name
  }
  dialogVisible.value = true;

};
const submitForm = async () => {
  if (addFormData.value) {
    if (addFormData.value.company_name && addFormData.value.index && addFormData.value.name && (addFormData.value.status == 1 || addFormData.value.status == 0)) {
      try {
        console.log("添加的数据:", addFormData.value, contact.value);
        await addDepartmentService(addFormData.value, contact.value);
        ElMessage.success('添加成功');
        dialogVisible.value = false;
        fetchDepartments();
        // 重置表单
        resetForm();
      } catch (error) {
        console.error('Login failed:', error)
        // 可以在这里添加错误处理，例如显示错误消息给用户
      }

    } else {
      ElMessage({
        message: '请填写必填的信息!',
        type: 'error',
      });
      return false;
    }

  }
}


//修改

const dialogVisible1 = ref(false);
const updateFormData = ref<DepartmentItem>({
  name: '',
  status: null,
  index: null,
  company_name: '',
  create_time: '',
  id: null,
});
const editMeetings = async (index: number, row: any) => {

  updateFormData.value = {
    name: row.name,
    index: row.index,
    create_time: row.create_time,
    company_name: row.company_name,
    id: row.id,
    status: row.status,
  };

  if (row.parent) {
    console.log("父节点的数据:", row.parent);
  } else {
    // 顶层节点
    updateFormData.value.company_name = "测盟汇";
    updateFormData.value.id = row.companyId;
  }
  contact.value = await getContactInfo(updateFormData.value);

  dialogVisible1.value = true;
};
const submitForm1 = async () => {

  if (updateFormData.value) {
    if (updateFormData.value.company_name && updateFormData.value.index && updateFormData.value.name && (updateFormData.value.status == 1 || updateFormData.value.status == 0)) {
      try {
        await updateDepartmentService(updateFormData.value, contact.value);
        ElMessage.success('修改成功');
        dialogVisible1.value = false;
        fetchDepartments();
        // 重置表单
        resetForm();
      } catch (error) {
        console.error('Login failed:', error)
        // 可以在这里添加错误处理，例如显示错误消息给用户
      }

    } else {
      ElMessage({
        message: '请填写必填的信息!',
        type: 'error',
      });
      return false;
    }

  }
};
//删除部门
const deleteDepartment = async (index: number, row: any) => {
  console.log("删除的数据:", row.name, row.company_name);
  const company_name = row.company_name;
  const name = row.name;
  ElMessageBox.confirm('确定删除该' + company_name+'的'+ name+ '吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 实现删除功能
    await deleteDepartmentService(row.name, row.company_name);
    ElMessage.success('删除成功');
    fetchDepartments();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
  
};

//全部展开/全部关闭
const allExpanded = ref(false);
const allExpandedNames = ref<string[]>([]);

const allNames = computed(() => {
  const names: string[] = [];
  // 添加第一级的 name
  if (rootData.value[0]) {
    names.push('1');
  }
  // 添加第二级的 name
  tableData.value.forEach(item => {
    names.push(item.name);
    // 添加第三级的 name
    item.departmentList.forEach(deprt => {
      names.push(deprt.name);
    });
  });

  return names;
});

const toggleAll = () => {
  allExpanded.value = !allExpanded.value;
  if (allExpanded.value) {
    allExpandedNames.value = allNames.value;
  } else {
    allExpandedNames.value = [];
  }
};

</script>

<style scoped>
.course {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 1200px;
  padding: 20px;
  margin: 0 auto;
}

.search-section {
  margin-bottom: 0px;
  width: 100%;
}

.button-section {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.label-text {
  font-weight: bold;
  /* 设置文字粗细为粗体 */
  color: #6c6b6b;
  /* 设置文字颜色为深灰色 */
  font-size: 14px;
  /* 设置文字大小为16像素 */
}

.nameclp {
  margin-right: 625px;
  /* 控制 name 之间的距离 */
}

.stateclp {
  margin-right: 120px;
  /* 控制 name 之间的距离 */
}

.nameclp2nd {
  width: 100px;
  text-align: left;
  margin-left: 25px;
  margin-right: 540px;
}

.sndBtn1 {
  margin-right: 20px;
}

.nameclp3rd {
  width: 100px;
  text-align: left;
  margin-left: 80px;
  margin-right: 75px;
}

.stateclp3rd {
  margin-right: 120px;
}

.trdBtn1 {
  margin-right: 20px;
}

.index {
  width: 25px;
  margin-right: 40px;
}

.creat_time {
  width: 200px;
  margin-right: 145px;
}
</style>
